package com.jp.knowledge.fragment;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.foamtrace.photopicker.PhotoPickerActivity;
import com.foamtrace.photopicker.SelectModel;
import com.foamtrace.photopicker.intent.PhotoPickerIntent;
import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.logic.PersonLogic;
import com.jp.knowledge.logic.UploadLogic;
import com.jp.knowledge.model.AuthInfo;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.activity.HelpCatePageActivity;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.util.ImageLoadUtil;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.util.SpanUtils;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;
import java.util.UUID;

/**
 * @author jiayen     2017-03-30 17:14:00
 *         认领组织
 */
public class JoinOrgnazitionFragment extends BaseFragment implements View.OnClickListener, ResultSubscriber.OnResultListener, JpApplication.SendMsgTimerCallBack {


	private OrganizaModel company;

	private String[] companyNames;//= new String[]{"广州信息","广州创将","广州信息","广州创将","广州信息","广州创将","广州信息","广州创将","广州信息","广州创将"};
	private static final int SELECT_HEAD_IMG_CODE = 0x01;
	private final int VERIFY_CODE = 0x000002;//获取验证码
	private final int SUBMIT_CODE = 0x000003;//验证提交
	private static final int GET_ORGANIZE_LIST_CODE = 0x000004;
	private UserData userData;

	@ViewInject(R.id.sure_btn)
	private TextView sure;
	@ViewInject(R.id.image)
	private ImageView imgIcon;
	@ViewInject(R.id.image_layout)
	private RelativeLayout imgLayout;
	@ViewInject(R.id.image_icon)
	private ImageView img;
	@ViewInject(R.id.name)
	private EditText nameEdit;
	@ViewInject(R.id.legal_person)
	private EditText legalPerson;
	@ViewInject(R.id.auth_code)
	private EditText authCode;
	@ViewInject(R.id.simple_company_name)
	private EditText simpleCompanyName;
	@ViewInject(R.id.fail_text)
	private TextView failText;
	@ViewInject(R.id.auth_code_btn)
	private TextView authBtn;
	@ViewInject(R.id.tel_phone)
	private TextView telBtn;
	@ViewInject(R.id.vercode_layout)
	private LinearLayout vercodeLayout;
	@ViewInject(R.id.img_tip)
	private TextView imgTip;
	@ViewInject(R.id.simple_company_name_layout)
	private LinearLayout simpleNameLayout;
	@ViewInject(R.id.my_role_tv_agree)
	private TextView agreementBtn;

	private String imgPath;
	private View mView;
	private String paramId;
	private int companyState;//审核状态   0未认证，1已认证，2认证中 3，不通过
	private int time;

	public JoinOrgnazitionFragment newInstance(OrganizaModel company) {
		this.company = company;
		if (company != null) {
			companyState = company.getCompanyState();
			int companyType = company.getCompanyType();
			if (companyType == 2)
				paramId = company.getClassId();
			else
				paramId = company.getCompanyId();
		}
		return this;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_join_orgnazition, container, false);
		x.view().inject(this, mView);
		init();
		return mView;
	}

	protected void init() {
		userData = application.getUserData();
		nameEdit.setText(userData.getUsername());
		simpleCompanyName.setText(company.getCompanyName());
		setBtnStatus();
		sure.setOnClickListener(this);
		imgLayout.setOnClickListener(this);
		authBtn.setOnClickListener(this);
		agreementBtn.setOnClickListener(this);

		final String tel = "020-82513714";
		ClickableSpan clickableSpan = new ClickableSpan() {
			@Override
			public void onClick(View widget) {
				Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
			}
		};
		SpannableStringBuilder stringBuilder = new SpanUtils(mContext)
				.append("验证结果将在两个工作日内回复。如有疑问，请拨打")
				.setForegroundColor(getResources().getColor(R.color.font_gray_light))
				.append(tel)
				.setForegroundColor(getResources().getColor(R.color.experience_edit_text_color))
				.setClickSpan(clickableSpan)
				.append("咨询。")
				.setForegroundColor(getResources().getColor(R.color.font_gray_light))
				.create();
		telBtn.setText(stringBuilder);
		telBtn.setMovementMethod(LinkMovementMethod.getInstance());
		time = application.getNextSendMsgTime();
		if (time > 0)
			startTime(0);
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.sure_btn://提交审核
				submitSure();
				break;
			case R.id.image_layout://选择图片
				gotoSelectHeadIcon();
				break;
			case R.id.auth_code_btn://发送验证码
				sendAuthCode();
				break;
			case R.id.my_role_tv_agree://用户协议
				startActivity(new Intent(mContext, HelpCatePageActivity.class)
						.putExtra("pageId", "9bb9f809-c29f-b656-9c90-7104b0caccc1")
						.putExtra("title", "认证服务协议"));
				break;
			default:
				break;
		}
	}

	private void sendAuthCode() {
		userData = application.getUserData();
		if (userData != null) {
			JsonObject param = new JsonObject();
			param.addProperty("phone", userData.getPhone());
			HttpHelper.getInstance(mContext).getOrganizaSmsCode(param, VERIFY_CODE, this);
		} else {
			ToasUtil.toast(mContext, "用户信息为空");
		}
	}

	private void submitSure() {
		int companyType = company.getCompanyType();
		final JsonObject param = new JsonObject();
		String companyName = simpleCompanyName.getEditableText().toString();
		String userName = nameEdit.getEditableText().toString();
		String legal = legalPerson.getEditableText().toString();
		String code = authCode.getEditableText().toString();
		if (companyType != 2 && TextUtils.isEmpty(companyName)) {
			ToasUtil.toast(mContext, "请输入组织简称!");
		} else if (TextUtils.isEmpty(userName)) {
			ToasUtil.toast(mContext, "请输入姓名!");
		} else if (TextUtils.isEmpty(legal) && companyType != 2) {//学校不存在法人
			ToasUtil.toast(mContext, "请输入法人!");
//		} else if(TextUtils.isEmpty(code)){
//            ToasUtil.toast(mContext,"请输入验证码!");
        } else if (TextUtils.isEmpty(imgPath)) {
			ToasUtil.toast(mContext, "请选择营业执照!");
		} else {
			param.addProperty("name", userName);
			param.addProperty("legalPerson", legal);
			param.addProperty("verifyCode", code);
			param.addProperty("id", paramId);
			param.addProperty("type", company.getCompanyType());//组织类型 1是公司
			if (company.getCompanyType() != 2)       // 非学校需要传公司简称
				param.addProperty("organizaName", company.getCompanyName());
			String imgUrl = company.getAuthInfo().getAdditional();
			if (!TextUtils.isEmpty(imgPath)) {
				String key = String.format("company/auth/%s/%s/%s", company.getCompanyId(), UploadLogic.getTime(), UploadLogic.getName());
				UploadLogic uploadLogic = new UploadLogic(mContext, imgPath, key);
				uploadLogic.setCallBack(new UploadLogic.UploadCallBack() {
					@Override
					public void done(boolean success) {
						loadingDialog.cancel();
						ToasUtil.toast(mContext, success ? "图片上传成功!" : "图片上传失败!");
					}
					@Override
					public void uploadSuccess(String url) {
						loadingDialog.cancel();
						param.addProperty("additional", url);
						HttpHelper.getInstance(mContext).authOrganize(param, SUBMIT_CODE, JoinOrgnazitionFragment.this);
					}
				});
				uploadLogic.uploadImage();
				loadingDialog.show();
			} else {//代表有图片是 重新提交
				if (!TextUtils.isEmpty(imgUrl)) {
					param.addProperty("additional", imgUrl);//附加照片
					HttpHelper.getInstance(mContext).authOrganize(param, SUBMIT_CODE, JoinOrgnazitionFragment.this);
				} else {
					ToasUtil.toast(mContext, "请选择营业执照!");
				}
			}
		}
	}

	/**
	 * 设置按钮状态
	 */
	private void setBtnStatus() {
		int companyType = company.getCompanyType();
		if (companyType == 2) {//代表是学校
			mView.findViewById(R.id.legal_person_layout).setVisibility(View.GONE);//隐藏法人
			simpleNameLayout.setVisibility(View.GONE);//隐藏简称
			imgTip.setText("学生证");
		}
		AuthInfo authInfo = company.getAuthInfo();
		if (companyState == 0) {//  0未认证，1已认证，2认证中 3，不通过
			sure.setText("提交审核");
			sure.setBackgroundResource(R.drawable.selector_btn_blue);
			sure.setTextColor(getResources().getColor(R.color.white));
			sure.setEnabled(true);
		} else if (companyState == 1) {
			if (authInfo != null) {
				legalPerson.setText(authInfo.getLegalPerson());
				img.setVisibility(View.VISIBLE);
				ImageLoadUtil.load(mContext, authInfo.getAdditional(), img);
				vercodeLayout.setVisibility(View.GONE);
			}
			sure.setText("认领审核通过");
			sure.setEnabled(false);
			sure.setTextColor(getResources().getColor(R.color.theme_color));
		} else if (companyState == 2) {
			sure.setText("认领审核中");
			sure.setEnabled(false);
			sure.setTextColor(getResources().getColor(R.color.google_red));
			if (authInfo != null) {
				nameEdit.setText(authInfo.getName());
				simpleCompanyName.setText(authInfo.getOrganizaName());
				legalPerson.setText(authInfo.getLegalPerson());
				String url = authInfo.getAdditional();
				if (!TextUtils.isEmpty(url)) {
					img.setVisibility(View.VISIBLE);
					ImageLoadUtil.load(mContext, url, img);
					vercodeLayout.setVisibility(View.GONE);
				}
			}
		} else if (companyState == 3) {
			sure.setText("重新提交");
			sure.setBackgroundResource(R.drawable.selector_btn_blue);
			sure.setTextColor(getResources().getColor(R.color.white));
			sure.setEnabled(true);
			if (authInfo != null) {
				nameEdit.setText(authInfo.getName());
				simpleCompanyName.setText(authInfo.getOrganizaName());
				legalPerson.setText(authInfo.getLegalPerson());
				img.setVisibility(View.VISIBLE);
				ImageLoadUtil.load(mContext, authInfo.getAdditional(), img);
				failText.setText("审核失败原因：\n" + authInfo.getAuthExplain());
				failText.setVisibility(View.VISIBLE);
			}
		}
	}

	private void gotoSelectHeadIcon() {
		PhotoPickerIntent intent = new PhotoPickerIntent(mContext);
		intent.setSelectModel(SelectModel.MULTI);
		intent.setMaxTotal(1);
		intent.setShowCarema(true);
		startActivityForResult(intent, SELECT_HEAD_IMG_CODE);
		getActivity().overridePendingTransition(R.anim.anim_enter, 0);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == SELECT_HEAD_IMG_CODE && data != null) {
			List<String> imageSelectedPaths = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
			if (imageSelectedPaths == null && imageSelectedPaths.size() == 0)
				return;
			img.setVisibility(View.VISIBLE);
			imgPath = imageSelectedPaths.get(0);
			ImageLoadUtil.load(mContext, imgPath, img);
		}
	}

	@Override
	public void onStart(int requestType) {
		loadingDialog.show();
	}

	@Override
	public void onCompleted(int requestType) {
		loadingDialog.cancel();
	}

	@Override
	public void onError(int requestType) {
		onCompleted(requestType);
	}

	@Override
	public void onNext(IModel data, int requestType) {
		if(data.getErrcode() != 0){
			ToasUtil.toast(mContext, data.getMessage());
			onError(requestType);
		} else if (requestType == VERIFY_CODE) {//获取验证码成功
			time = 60;
			application.setNextSendMsgTime(time);
			startTime(0);
		} else if (requestType == SUBMIT_CODE) {//上传图片成功
			new PersonLogic(mContext).getUserData();//刷新用户信息
			companyState = 2;
			AuthInfo authInfo = company.getAuthInfo();
			authInfo.setOrganizaName(simpleCompanyName.getEditableText().toString());
			authInfo.setName(nameEdit.getEditableText().toString());
			authInfo.setLegalPerson(legalPerson.getEditableText().toString());
			setBtnStatus();
			ToasUtil.toast(mContext, "验证成功!");
			getActivity().finish();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	public void timerCallBack(int time) {
		if(authBtn == null)
			return;
		if (time > 0) {
			authBtn.setEnabled(false);
			authBtn.setTextColor(getResources().getColor(R.color.font_gray_think));
			authBtn.setBackgroundResource(R.drawable.btn_rbg_gray);
			authBtn.setText("重新获取(" + time + "秒)");
		} else {
			authBtn.setBackgroundResource(R.drawable.btn_blue);
			authBtn.setTextColor(getResources().getColor(R.color.white));
			authBtn.setText("获取验证码");
			authBtn.setEnabled(true);
		}
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (--time >= 0) {
				application.setNextSendMsgTime(time);
				timerCallBack(time);
				startTime(1000);
			} else {
				application.setNextSendMsgTime(0);
			}
		}
	};

	private void startTime(int time) {
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				handler.sendEmptyMessage(0);
			}
		}, time);
	}
}
